import React, { useEffect, useRef } from 'react';
import { Button, Input, Spin, Typography } from 'antd';
import type { GetProps } from 'antd';
import { tonmi } from 'tonmi';
import logo from '@assets/a1.png';
import logo2 from '@assets/a4.png';
import failpng from '@assets/a2.png';
import okpng from '@assets/a3.png';

type OTPProps = GetProps<typeof Input.OTP>;
export default function AuthPage(props: any) {
  const loaded = useRef(false);
  const [mode, setMode] = React.useState("init");

  const read_key = (): string => {
    const uri = location.href;
    let key = uri.substring(uri.lastIndexOf('/')+1, uri.length);
    const ix1 = key.indexOf('?');
    if (ix1 != -1)  key = key.substring(0, ix1);
    const ix2 = key.indexOf('#');
    if (ix2 != -1)  key = key.substring(0, ix2);
    return key;
  };
  const create_rao = (): string => {
    const _now =new Date();
    const _end = new Date(_now);
    _end.setMinutes(_end.getMinutes() + 5);
    const _base = new Date(Date.UTC(_end.getFullYear()-1, 4, 20)); // 基准
    const base_year_tag = _base.getFullYear()%10;
    const minutes = Math.floor((_now.getTime() - _base.getTime()) / (60 * 1000));
    const minutes_d = Math.floor(minutes/5);
    const minutes_d2= minutes%5;
    const radom = (Math.random() * 10000 * 3.14) &0xf;
    const tag = ((radom<<28)|(base_year_tag<<24)| (minutes_d2 << 20) | (minutes_d))>>>0;
    const rao = tonmi.EncodeHex(tonmi.EncodeMorse(tag.toString()));
    return rao;
  };

  const get_status = (params: {[key: string]: string}) => {
    const xhr = new XMLHttpRequest();
    const url = "/api/afirewall";
    const queryString = new URLSearchParams(params).toString();
    xhr.open("GET", `${url}?${queryString}`);
    
    xhr.onload = function() {
      if (xhr.status >= 200 && xhr.status < 300) {
        console.log(xhr.responseText);
        if (xhr.responseText == ":ok") setMode("ok");
        else setMode("pass");
      }
    };
    
    xhr.onerror = function() {
      console.error("网络错误");
    };
    
    xhr.send();
  }

  useEffect(() => {
    if (loaded.current) return;
    loaded.current = true;

    const rao = create_rao();
    const key = read_key();
    const hash = tonmi.GetSM3(key);
    
    const data = tonmi.EncryptSM4(hash, tonmi.EncodeHex(tonmi.EncodeMorse(rao)));
    get_status({"v": data, "rao": rao});
  }, []);

  const onChange: OTPProps['onChange'] = (pwd: string) => {
    setMode("check");
    const rao = create_rao();
    const key = read_key();
    const hash = tonmi.GetSM3(key);
    const ppwd = tonmi.EncryptSM4(hash, pwd);
    const password = tonmi.GetSha3_512(rao+ppwd);
    const data = tonmi.EncryptSM4(hash, tonmi.EncodeHex(tonmi.EncodeMorse(rao)));

    const xhr = new XMLHttpRequest();
    const url = "/api/afirewall";
    xhr.open("POST", url, true); 
    xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    xhr.onload = function() {
      if (xhr.status >= 200 && xhr.status < 300) {
        try {
          if (xhr.responseText == ":ok"){
            setMode("ok");
            return;
          }
        } catch (e) {
          console.error("JSON 解析失败:", e);
        }
      }
      setMode("fail");
      setTimeout(()=> setMode("pass"),3000);
    };

    xhr.onerror = function() {
      setMode("fail");
      setTimeout(()=> setMode("pass"),3000);
    };

    const payload = { "rao": rao, "password": password, "data": data };
    xhr.send(JSON.stringify(payload)); // 发送 JSON 字符串
  };
  let lasttime = Date.now();
  const formatter: OTPProps['formatter'] = (value: string) => {
    const now = Date.now();
    if (value.length > 1 && (now-lasttime) < 100){
        const _1 = value [value.length-1];
        const _2 = value [value.length-2];
        if (_1 == _2) {
            value = value.substring(0, value.length-1);
            return value;
        }
    }
    lasttime = now;
    return value;
  };
  const sharedProps: OTPProps = {
    onChange,
    formatter,
  };
  const on_rmauth = () => {
    const rao = create_rao();
    const key = read_key();
    const hash = tonmi.GetSM3(key);
    
    const data = tonmi.EncryptSM4(hash, tonmi.EncodeHex(tonmi.EncodeMorse(rao)));
    setMode("check");
    get_status({"v": data, "rao": rao, "rm": "all"});
  };
  return (<>
    <div style={{ display: 'flex', alignItems: 'center', position: "absolute", top: 0, left: 0, opacity: 0.95}}>
      <img style={{height:"52px"}} src={logo}/><img style={{height:"28px"}} src={logo2}/>
    </div>
    {mode == "init" ? <Spin />:<></>}
    {mode == "pass" ? <Input.OTP autoFocus variant="filled" mask="⚫" {...sharedProps} />:<></>}
    {mode == "check" ? <Spin />:<></>}
    {mode == "ok"? <>
    <img style={{height: "32px"}} src={okpng} />
    <span>已经授权</span>
    <Button size="small" onClick={on_rmauth}>取消授权</Button>
    </>:<></>}
    {mode == "fail"? <><img style={{height: "32px"}} src={failpng} /> <span>请求驳回</span></>:<></>}
  </>);
}